/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: RxWebSecurityConfigurer
 * @Package com.rx.core.bean
 * @Description: 安全配置
 * @author: 陈锦韬
 * @date: 2021\6\23 0023
 * @version V1.0
 * @Copyright: 2021 陈锦韬  All rights reserved.
 */
package com.rx.core.bean;

import com.rx.core.iface.IUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.error.OAuth2ExceptionRenderer;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.annotation.Resource;

/**
 * @author: Administrator
 * @Description: 安全配置
 * @date: 2021\6\23 0023
 */
@Configuration
@ConditionalOnBean(name = "rxUserDetailsService")
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@Order(10)
public class RxWebSecurityConfigurer  extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 成功处理器
     */
    @Autowired
    private RxSuccessHandler rxSuccessHandler;

    /**
     * 失败处理
     */
    @Autowired
    private RxFailHandler rxFailHandler;

    @Autowired
    private RxLogoutSuccessHandler rxLogoutSuccessHandler;

    @Bean
    public AuthenticationEntryPoint createAuthenticationEntryPoint() {
        //获取用户账号密码及权限信息
        return new CustomAuthenticationEntryPoint();
    }

    @Bean
    @ConditionalOnBean(name = "rxConfigBean")
    public PasswordEncoder passwordEncoder() {
        // 设置默认的加密方式（强hash方式加密）
        return new RxBCryptPasswordEncoder();
    }



    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManager();
    }

    @Resource(name="rxUserDetailsService")
    private IUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //配置认证方式等
        LoginAuthenticationProvider provider = new LoginAuthenticationProvider(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        auth.authenticationProvider(provider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                //.antMatchers("/oauth/.*").permitAll()
                //不是fully 可能導致http://localhost:8086/oauth/authorize 接口無權限
                //.anyRequest().authenticated()
                .antMatchers("/login/.*").denyAll()
                //.anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .successHandler(rxSuccessHandler)
                .failureHandler(rxFailHandler)
                .and().logout()
                .logoutSuccessHandler(rxLogoutSuccessHandler)
                // 重新定义登录页面URL
                //.loginPage("/login-view")
                // 登录校验URL
                //.loginProcessingUrl("/login")
                // 登录成功重定向
                //.successForwardUrl("/login-success")
                //.permitAll()
                .and().exceptionHandling();

        // 自定义异常返回
//        ResourceServerSecurityConfigurer configurer = http.getConfigurer(ResourceServerSecurityConfigurer.class);
//        OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
//        OAuth2ExceptionRenderer oAuth2ExceptionRenderer = new RxOAuth2ExceptionRenderer();
//        authenticationEntryPoint.setExceptionRenderer(oAuth2ExceptionRenderer);
//        configurer.authenticationEntryPoint(authenticationEntryPoint);
    }
}
